//
//  HomeView.swift
//  Notepad
//
//  Created by 左忠飞 on 2021/1/18.
//

import UIKit

class HomeView: UIScrollView {

    //定一列间距
    let interitemSpacing:CGFloat = 15
    //定义行间距
    let lineSpacing:CGFloat = 25
    //用于存放所有分组标题的数组
    var dataArray:Array<String>?
    //用于存放所有分组按钮的数组
    var itemArray:Array<UIButton> = Array<UIButton>()
    
    var homeButtonDelegate:HomeButtonDelegate?
    
    
    //提供一个跟新布局的方法
    func updateLayout(){
        //根据视图尺寸计算每个按钮的宽度
        let itemWidth = (self.frame.size.width - CGFloat(4 * interitemSpacing)) / 3
        //计算每个按钮的高度
        let itemHeight = itemWidth / 3 * 4
        
        //先将界面上已有的按钮移除
        itemArray.forEach { (element) in
            element.removeFromSuperview()
        }
        
        //移除数组所有元素
        itemArray.removeAll()
        
        //j进行布局
        if dataArray != nil && !dataArray!.isEmpty {
            //遍历数组
            for index in 0..<dataArray!.count {
                let btn = UIButton(type: .system)
                btn.setTitle(dataArray![index], for: .normal)
                //计算按钮位置
                let x:CGFloat = interitemSpacing + CGFloat((index % 3)) * (itemWidth + interitemSpacing)
                let y:CGFloat = CGFloat(lineSpacing)+CGFloat(index/3) * (itemHeight + lineSpacing)
                
                btn.frame = CGRect(x: x,
                                   y: y,
                                   width: itemWidth,
                                   height: itemHeight)
                btn.backgroundColor = UIColor(red: 1, green: 242/255, blue: 216/255, alpha: 1)
                //设置按钮圆角
                btn.layer.masksToBounds = true
                btn.layer.cornerRadius = 15
                btn.setTitleColor(.gray, for: .normal)
                btn.tag = index
                btn.addTarget(self, action: #selector(btnClick(btn:)), for: .touchUpInside)
                self.addSubview(btn)
                //将按钮添加到数组中
                itemArray.append(btn)
            }
            //设置滚动视图的内容尺寸
            self.contentSize = CGSize(width: 0, height: itemArray.last!.frame.origin.y + itemArray.last!.frame.size.height+lineSpacing)
        }
    }
    
    //按钮的触发方法
    @objc func btnClick(btn:UIButton){
        print(dataArray![btn.tag])
        if homeButtonDelegate != nil {
            homeButtonDelegate?.homeButtonClick(title: dataArray![btn.tag])
        }
    }
}

protocol HomeButtonDelegate {
    func homeButtonClick(title:String)
}
